<?php
use Core\Constant;

$allRoles = $this->allRoles;
$allPrivileges = $this->allPrivileges;
?>

<div class="ad_title_ctn">
    <h2>Quản lý quyền - vai trò</h2>
</div>

<div class="ad_content_ctn">
    <div class="role_control_ctn">
        <a class="k-button k-button-icontext k-grid-add" id="btnAddRole">
            <span class="k-icon k-add"></span>
            Tạo mới
        </a>
    </div>
    <div class="role_content_ctn">
        <div>

            <table class="tblAdRolePrivilege"  cellpadding="5px" cellspacing="0px" style="width: 100%">
                <tr>
                    <td style="width: 200px;" class="">

                    </td>
                    <?php
                    $roleNum =  count($allRoles);
                    $width =  intval(85/$roleNum); //headache issue, how to get exact width solution and set to PHP variable
                    foreach ($allRoles as $aRole) {
                        $disabled = '';
                        if($aRole->modifiable == 0)
                            $disabled = 'disabled';
                        echo '<td style="width: '.$width.'%"><span class="header">'.$aRole->name.
                            ' </span><input value="'.$aRole->id.'" '.$disabled.' type="checkbox" class="chkParent chkAll'.$aRole->id.'">
                          <span></span>';
                        if($aRole->modifiable != 0){
                            echo '<a class="k-button k-button-icontext k-grid-delete" href="javascript:deleteRole('.$aRole->id.')" title="Xóa">
                            <span class="k-icon k-delete"></span>

                          </a>';
                            echo '<a class="k-button k-button-icontext grd_edit_btn  k-grid-edit" href="javascript:editRole('.$aRole->id.');" title="Sửa">
                            <span class="k-icon k-edit"></span>
                          </a>
                        </td>';
                        }
                    }
                    ?>

                </tr>
                <?php
                foreach ($allPrivileges as $aPrivilege) {
                    echo '<tr>';
                    echo '<td><span class="spnRoleTooltip"  title="'.$aPrivilege->description.'">'.$aPrivilege->name.
                        ' </span></td>';
                    $allPrivRole = $aPrivilege->getBelongedRole();
                    foreach ($allRoles as $aRole) {
                        $checked ='';
                        foreach ($allPrivRole as $myRole) {
                            if($myRole->id == $aRole->id){
                                $checked = 'checked';
                                break;
                            }
                        }
                        $disabled = '';
                        if($aRole->code == Constant::$ROLE_ADMIN_CODE)
                            $disabled = 'disabled';

                        echo '<td>
                        <input value="'.$aPrivilege->id.'_'.$aRole->id.'" '.$checked.' '.$disabled.' type="checkbox" class="chkChild chkItem'.$aRole->id.'" name="chkRolePrivilege">
                        <span></span>
                    </td>';
                    }

                    echo '</tr>';
                }

                ?>



            </table>



        </div>

    </div>
    <div id="wndAddRole"></div>

    <script type="text/x-kendo-template" id="addRoleTemplate">
        <div id="add-staff-container">
            <dl>
                <dt style="padding: 5px"><div style="width: 70px; float:left"> Mã(*):</div>
                <input  id='txtRoleId'  name="txtRoleId" type="hidden"    value='#= id #'>
                <input  id='txtRoleCode'  name="txtRoleCode" class="k-textbox"  required  value='#= code #'>

                </dt>
                <dt style="padding: 5px"><div style="width: 70px;float:left"> Tên(*):</div>
                <input  class="k-textbox"  required  id='txtRoleName' value='#= name #'>


                </dt>
                <dt style="padding: 5px"><div style="width: 70px; float:left"> Mô tả:</div>
                <input style="width:300px"  class="k-textbox"  required  id='txtRoleDescription' value='#= description #'>

                </dt>
                <dt style="padding: 5px">
                    <span style="color:red" id="spnStatus"></span>
                </dt>
            </dl>
            <div style="padding: 10px 0px" >
                <a class="k-button k-button-icontext k-grid-update" href="javascript:saveRole()">
                    <span class="k-icon k-update"></span>
                    Lưu
                </a>
                <a class="k-button k-button-icontext k-grid-cancel" href="javascript:closeRoleWinPass()">
                    <span class="k-icon k-cancel"></span>
                    Cancel
                </a>
            </div>
        </div>
    </script>
    <script id="template" type="text/x-kendo-template">
        <p>#=target.data('title')#</p>
    </script>
    <script type="text/javascript">
        var loadingImage = '<img src="/public/images/icons/ajax_loading.gif">';
        $(document).ready(function() {
        <?php
        foreach ($allRoles as $aRole) {
            echo ' $.setupCheckGroup("chkAll'.$aRole->id.'","chkItem'.$aRole->id.'");';
        }
        ?>

            $(".chkParent").each(function(){
                $(this).change(function(){
                    roleId = $(this).val();
                    isSelected =  $(this).is(":checked")?1:0;
                    my = $(this);
                    $(this).next().html(loadingImage);
                    $.post('<?php echo '/admin/role/role-check-all-privilege'?>',{roleId:roleId, isSelected:isSelected},function(result){
                        my.next().html('');
                        if (result.success){
                            $('#error_ctn').addClass('blue_text').html('Gán quyền thành công');
                        }else{
                            $('#error_ctn').removeClass('blue_text').html(result.msg);
                            alert(result.msg);
                        }
                    },'json');
                })
            })

            $(".chkChild").each(function(){
                $(this).change(function(){
                    rolePrivilege = $(this).val();
                    tmpArr = rolePrivilege.split('_');
                    privilegeId = tmpArr[0];
                    roleId = tmpArr[1];
                    isSelected =  $(this).is(":checked")?1:0;
                    my = $(this);
                    $(this).next().html(loadingImage);
                    $.post('<?php echo '/admin/role/role-check-a-privilege'?>',
                            {privilegeId:privilegeId, roleId:roleId, isSelected:isSelected},function(result){
                        my.next().html('');
                        if (result.success){
                            $('#error_ctn').addClass('blue_text').html('Gán quyền thành công');
                        }else{
                            $('#error_ctn').removeClass('blue_text').html(result.msg);
                            alert(result.msg);
                        }
                    },'json');
                })
            })

            addRoleTemplate = kendo.template($("#addRoleTemplate").html());

            $(".tblAdRolePrivilege").kendoTooltip({
                filter: "span.spnRoleTooltip",
                content: kendo.template($("#template").html()),
                width: 200,
                height: 70,
                position: "top"
            });

            function doAdd(){
                wndAddRole.content(addRoleTemplate({"id":'',"code":'',"name":'',"description":""}));
                wndAddRole.center().open();
            }

            $('#btnAddRole').click(function(){
                doAdd();
            })






        });
        wndAddRole = $("#wndAddRole")
                .kendoWindow({
                    title: "Thêm role",
                    modal: true,
                    visible: false,
                    resizable: false,
                    width: 400,
                    activate: onActivateAddRole

                }).data("kendoWindow");
        $("#wndAddRole").keypress(function(event){
            //if the key press is ESC
            if (event.keyCode === 27) {
                //close the KendoUI window
                $("#wndAddRole").data("kendoWindow").close();
            }

            if(event.keyCode === 13) {
                saveRole();
            }
        });

        function onActivateAddRole(){
            $("#txtRoleCode").focus();
        }

        function closeRoleWinPass(){
            wndAddRole.close();
        }

        function saveRole(){
            if(!validateRoleSave())
                return;
            id = $("#txtRoleId").val();
            name = $("#txtRoleName").val();
            code = $("#txtRoleCode").val();
            description = $("#txtRoleDescription").val();

            $.post('<?php echo '/admin/role/save'  ?>',
                    {name:name,code:code,description:description, id:id}
                    ,function(result){
                        if (result.success){
                            closeRoleWinPass();
                            $("#spnStatus").html('');
                            location.reload();
                        }else{
                            $("#spnStatus").html(result.msg);
                        }
                    },'json');
        }



        function validateRoleSave(){
            if(!$("#txtRoleCode").val()){
                $("#spnStatus").html('Vui lòng nhập mã.');
                $("#txtRoleCode").focus();
                return false;
            }

            if(!$("#txtRoleName").val()){
                $("#spnStatus").html('Vui lòng nhập tên.');
                $("#txtRoleName").focus();
                return false;
            }


            return true;
        }
        function editRole(id){
            $.post('<?php echo '/admin/role/role-get-by-id'  ?>',
                    {id:id}
                    ,function(result){
                        if (result.success){
                            wndAddRole.title('Sửa role');
                            wndAddRole.content(addRoleTemplate(result.data));
                            wndAddRole.center().open();
                        }else{

                        }
                    },'json');
        }

        function deleteRole(id){

            r=confirm("Bạn có muốn xóa không?");
            if (r==true)
            {
                $.post('<?php echo '/admin/role/delete'  ?>',{id:id},function(result){
                    if (result.success){
                        $("#spnStatus").html('');
                        location.reload();
                    }else
                        $("#spnStatus").html(result.msg);
                },'json');
            }

        }
    </script>